package com.wlz.demo.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlz.demo.common.ResultUtil;
import com.wlz.demo.controller.dto.UserDTO;
import com.wlz.demo.entity.User;
import com.wlz.demo.service.IUserService;
import com.wlz.demo.utils.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * (User)表控制层
 * @since 2022-04-11 16:49:13
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired(required = true)
    private IUserService iUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static final String FILES_KEY = "FILES_GET_ALL";

    @PostMapping("/save")

    public ResultUtil<?> save(@RequestBody User user){
        boolean save = iUserService.save(user);
        if (save){
            return ResultUtil.success(200,"新增成功");
        }else {
            return ResultUtil.fail(500,"新增失败");
        }
    }

    @GetMapping("/list")
    public ResultUtil<?> list(){
        List<User> list = iUserService.list(null);
        if (list.size()!=0){
            return ResultUtil.success(200,"查询成功",list);
        }else {
            return ResultUtil.fail(500,"查询失败");
        }
    }

    @DeleteMapping("/delete")
//    @CacheEvict(value = "user",key = "'getAll'")
    public ResultUtil<?> delete(@PathParam(value = "id") Integer id){
        boolean b = iUserService.removeById(id);
        if (b){
            List<User> list = iUserService.list(null);
            return ResultUtil.success(200,"删除成功",list);
        }else {
            return ResultUtil.fail(500,"删除失败");
        }

    }

    @PutMapping("/updateById")

//    @CachePut(value = "user",key = "'getAll'")
    public ResultUtil<?> updateById(@RequestBody User user){
        boolean b = iUserService.updateById(user);
        if (b){
            User one = iUserService.getById(user.getId());
            return ResultUtil.success(200,"修改成功",one);
        }else {
            return ResultUtil.fail(500,"修改失败");
        }
    }

    //多个模糊查询+分页
    @GetMapping("/page")
    //cache缓存
//    @Cacheable(value = "user",key = "#pageNum+'-'+#pageSize+'-'+#username+'-'+#phone+'-'+#address")
//    @Cacheable(value = "user",key = "'getAll'")
    public IPage<User> pageLike(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(required=false) String username,
                                @RequestParam(required=false) String phone,
                                @RequestParam(required=false) String address
    ){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.like(username!=null,User::getUsername,username);
        lqw.like(phone!=null,User::getPhone,phone);
        lqw.like(address!=null,User::getAddress,address);
        IPage<User> iPage = new Page<>(pageNum,pageSize);
        IPage<User> page = iUserService.page(iPage,lqw);
        return page;
//        redis
        //1.从缓存中取出数据
        //2.取出的 json 是空的
        //3.从数据库取出数据
        //4.再缓存到redis
        //5.如果有就从redis拿数据
//        IPage<User> page;
//        String jsonStr = stringRedisTemplate.opsForValue().get(FILES_KEY);
//        if (jsonStr == null){
//            page = iUserService.page(iPage,lqw);
//            stringRedisTemplate.opsForValue().set(FILES_KEY, JSONUtil.toJsonStr(page));
//        }else {
//            page = JSONUtil.toBean(jsonStr, new TypeReference<IPage<User>>() {
//            },true);
//        }

//        return page;
    }

    //登录
    @PostMapping("/login")
    public ResultUtil<?> login(@RequestBody UserDTO userDTO){
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (username == "" || password == ""){
            return ResultUtil.fail(404,"账号或者密码不能为空");
        }
        boolean b = iUserService.login(userDTO);
        if (b){

            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getUsername,userDTO.getUsername());
            User one = iUserService.getOne(lqw);
            userDTO.setNickName(one.getNickName());

            //当登录成功的时候 设置token
            String token = TokenUtils.getToken(one.getId().toString(), one.getPassword());
            userDTO.setToken(token);
            userDTO.setId(one.getId());
            userDTO.setAvatarUrl(one.getAvatarUrl());


            return ResultUtil.success(200,"登录成功",userDTO);
        }else {
            return ResultUtil.fail(401,"账号或者密码错误");
        }
    }

    //注册
    @PostMapping("/register")
    public ResultUtil<?> register(@RequestBody UserDTO userDTO){

        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,userDTO.getUsername());
        List<User> list = iUserService.list(lqw);
        if (list.size() == 0){
            User user = new User();
            BeanUtils.copyProperties(userDTO,user);
            iUserService.save(user);
            return ResultUtil.success(200,"注册成功",userDTO);
        }else {
            return ResultUtil.fail(601,"该用户名太受欢迎了，请换一个");
        }
    }

    //导出
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        List<User> list = iUserService.list();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //只导出别名
        writer.setOnlyAlias(true);
        writer.write(list,true);

        //设置浏览器响应式的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();

    }

    //导入
    @PostMapping("/import")
    public Boolean importFile(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 读取第二行到最后一行数据 （为了忽略表头中文）
        reader.read(1, reader.getRowCount());
        List<User> list = reader.readAll(User.class);
        iUserService.saveBatch(list);
        return true;
    }


    //通过id查个人信息
    @GetMapping("/getOneByUsername/{username}")
    public ResultUtil<?> getById(@PathVariable String username){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,username);
        User one = iUserService.getOne(lqw);
        if ( one != null ){
            return ResultUtil.success(200,"查询成功",one);
        }else {
            return ResultUtil.fail(401,"查询失败");
        }
    }




}

